package com.cs.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cs.entity.Department;
import com.cs.listener.ExcelListener;
import com.cs.mapper.DepartmentMapper;
import com.cs.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {
    @Autowired
    private DepartmentMapper departmentMappermapper;


    @Override
    public void exportDeptData(HttpServletResponse response) throws IOException {
        //设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("dept", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        //查询数据库
        List<Department> list = baseMapper.selectList(null);
        EasyExcel.write(response.getOutputStream(), Department.class)
                .sheet("dept")
                .doWrite(list);

    }

    @Override
    public void importDeptData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), Department.class, new ExcelListener(departmentMappermapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
